// components/akCanvas/akCanvas.js
import akCanvasTool from "./akCanvasTool"

Component({
  lifetimes: {
    ready() {
      if (!this.id) {
        this.id = 'akCanvas'
      }
      this.initCanvas()
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    // 画布高度
    height: {
      type: String,
      value: '200px'
    },
    // 画布宽度
    width: {
      type: String,
      value: '200px'
    },
    drawObj: {
      type: Object,
      value: {}
    }
  },

  /**
   * 组件的初始数据
   */
  data: {

  },

  /**
   * 组件的方法列表
   */
  methods: {
    async initCanvas() {
      // 1. 根据配置,获取对应类型/位置/大小 绘制
      await this.initViewSize()

      // 获取画布
      this.createSelectorQuery()
        .select('#myCanvas') // 在 WXML 中填入的 id
        .fields({
          node: true,
          size: true
        })
        .exec(async (res) => {
          const canvas = new akCanvasTool(res[0])
          this.canvas = canvas
          // 2. 绘画
          this.draw()
        })
    },
    draw() {
      const {
        drawObj
      } = this.data
      const canvas = this.canvas
      const drawKeys = Object.keys(drawObj)
      for (let viewId of drawKeys) {
        const item = drawObj[viewId]
        switch (item.type) {
          case 'image':
            canvas.drawImage(item.url, item.left, item.top, item.width, item.height)
            break;
          case 'view':
            // 是否设置圆角
            if(item.radius){
              canvas.roundRect(item.left,item.top, item.width, item.height,item.radius,item.color)
            } else {
              canvas.setFillStyle(item.color)
              canvas.fillRect(item.left,item.top, item.width, item.height)
              canvas.fill()
            }

            // context.rect(0, 0, screenWidth, canvasHeight)
            // context.setFillStyle('#FFF8EF')
            // context.fill()
            break;
          case 'text':
            canvas.setFillStyle(item.color);
            canvas.setFontSize(item.fontSize);
            const textWidth = canvas.measureText(item.value).width;
            let lineList = []
            if (textWidth > item.width) {
              // 自动换行
              let lineNum = 0
              // 拆分字段, 逐个字添加
              for (let key of item.value) {
                let lineStr = ""
                if (lineList.length == lineNum) {
                  lineStr = ""
                  lineList.push("")
                } else {
                  lineStr = lineList[lineNum]
                }
                const nextText = lineStr + key
                const textWidth = canvas.measureText(nextText).width;
                if (textWidth > item.width) {
                  lineList.push(key)
                    ++lineNum
                } else {
                  lineList[lineNum] = nextText
                }
              }
            } else {
              lineList.push(item.value)
            }

            // 字体:水平对齐
            let left = 0
            canvas.setTextAlign(item.textAlign);
            switch (item.textAlign) {
              case 'center': // 居中
                left = item.left + item.width / 2
                break
              case 'right': // 右
                left = item.left + item.width
                break
              case 'left': // 左
              default:
                left = item.left
                break
            }
            let top = item.top
            // 估算高度
            let height = item.height / lineList.length
            // 文字的垂直对齐方式 top,middle,bottom
            const textBaseline = item.textBaseline || 'middle'
            canvas.setTextBaseline(textBaseline);
            switch (textBaseline) {
              case 'middle': // 居中
                // top = item.top + height / 2
                // 注意:1.2倍是css美术上的视觉居中
                top = item.top + (height / 2) * 1.2
                break
              case 'bottom': // 底部
                top = item.top + height
                break
              case 'top': // 顶部
              default:
                top = item.top
                break
            }
            // 换行显示
            for (let lineIndex in lineList) {
              const lineItem = lineList[lineIndex]
              const lineTop = top + height * lineIndex
              canvas.fillText(lineItem, left, lineTop);
            }
            break;
        }
      }
      // canvas.drawImage('https://www.baidu.com/img/flexible/logo/pc/result.png')
      // canvas.drawImage('https://www.baidu.com/img/flexible/logo/pc/result.png', 100, 100)
      canvas.draw()
    },

    async initViewSize() {
      const {
        drawObj
      } = this.data
      let viewIdList = Object.keys(drawObj)
      const promiseList = []
      for (let viewId of viewIdList) {
        promiseList.push(new Promise(resolve => {
          wx.createSelectorQuery()
            .select('#' + viewId)
            .fields({
              rect: true,
              size: true
            })
            .exec((node) => {
              drawObj[viewId] = {
                ...node[0],
                ...drawObj[viewId]
              }
              resolve()
            })
        }))
      }
      await Promise.all(promiseList)
      // const parentTarget = getCurrentPages()[getCurrentPages().length - 1]
      this.setData({
        drawObj
      })
      this.resetParentData()
    },
    resetParentData() {
      const parentTarget = getCurrentPages()[getCurrentPages().length - 1]
      parentTarget.setData({
        [this.id + 'Target']: this.data
      })
    },
  }
})